package com.fsj.admin.common.controller;

import com.fsj.admin.common.config.Constant;
import com.fsj.admin.common.domain.DictDO;
import com.fsj.admin.common.domain.DictTaskDO;
import com.fsj.admin.common.service.DictService;
import com.fsj.admin.common.service.DictTaskService;
import com.fsj.admin.common.utils.PageUtils;
import com.fsj.admin.common.utils.Query;
import com.fsj.admin.common.utils.R;
import com.fsj.admin.common.utils.UploadImageUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典表
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2017-09-29 18:28:07
 */

@Controller
@RequestMapping("/common/dict")
public class DictController extends BaseController {
    @Autowired
    private DictService dictService;
    @Autowired
    private DictTaskService dictTaskService;

    @GetMapping()
    @RequiresPermissions("common:dict:dict")
    String dict() {
        return "common/dict/dict";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("common:dict:dict")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<DictDO> dictList = dictService.list(query);
        int total = dictService.count(query);
        PageUtils pageUtils = new PageUtils(dictList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("common:dict:add")
    String add() {
        return "common/dict/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("common:dict:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        DictDO dict = dictService.get(id);
        model.addAttribute("dict", dict);
        return "common/dict/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("common:dict:add")
    public R save(DictDO dict) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (dictService.save(dict) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("common:dict:edit")
    public R update(DictDO dict) {
        DictDO dictDO = dictService.get(dict.getId());
        if (dictDO == null) {
            return R.error("配置有误");
        }

        if (Constant.INVITER_REWARD.equals(dictDO.getType()) || Constant.SHOP_REWARD.equals(dictDO.getType())
                || Constant.ORDER_REWARD.equals(dictDO.getType()) || Constant.SETTLE_ORDER_SHOP.equals(dictDO.getType())) {
            Map<String, Object> params = new HashMap<>(1);
            params.put("dictId", dictDO.getId());
            List<DictTaskDO> list = dictTaskService.list(params);
            if (!CollectionUtils.isEmpty(list)) {
                list.get(0).setOldValue(dictDO.getValue());
                list.get(0).setDictValue(dict.getValue());
                list.get(0).setStatus("0");
                dictTaskService.update(list.get(0));
            } else {
                DictTaskDO dictTaskDO = new DictTaskDO();
                dictTaskDO.setDictId(dictDO.getId());
                dictTaskDO.setDictType(dictDO.getType());
                dictTaskDO.setOldValue(dictDO.getValue());
                dictTaskDO.setDictValue(dict.getValue());
                dictTaskDO.setStatus(Constant.GENERAL_ZERO);
                dictTaskService.save(dictTaskDO);
            }

            return R.ok("修改成功，配置将在第二天生效");
        } else {
            dictService.update(dict);
        }
        return R.ok("修改成功");
    }

    /**
     * 修改二维码
     */
    @ResponseBody
    @RequestMapping("/updateQrCode")
    @RequiresPermissions("common:dict:edit")
    public R updateQrCode(DictDO dict) {
        if (StringUtils.isBlank(dict.getType()) || StringUtils.isBlank(dict.getValue())) {
            return R.error("参数不正确");
        }

        List<DictDO> list = dictService.listByType(dict.getType());
        if (CollectionUtils.isEmpty(list)) {
            return R.error("暂无该配置，请先添加");
        }

        list.get(0).setValue(dict.getValue());
        dictService.update(list.get(0));
        return R.ok("修改成功");
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("common:dict:remove")
    public R remove(Long id) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        if (dictService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("common:dict:batchRemove")
    public R remove(@RequestParam("ids[]") Long[] ids) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        dictService.batchRemove(ids);
        return R.ok();
    }

    @GetMapping("/type")
    @ResponseBody
    public List<DictDO> listType() {
        return dictService.listType();
    }

    ;

    // 类别已经指定增加
    @GetMapping("/add/{type}/{description}")
    @RequiresPermissions("common:dict:add")
    String addD(Model model, @PathVariable("type") String type, @PathVariable("description") String description) {
        model.addAttribute("type", type);
        model.addAttribute("description", description);
        return "common/dict/add";
    }

    @ResponseBody
    @GetMapping("/list/{type}")
    public List<DictDO> listByType(@PathVariable("type") String type) {
        // 查询列表数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("type", type);
        List<DictDO> dictList = dictService.list(map);
        return dictList;
    }

    /**
     * 上传图片
     *
     * @param request
     * @throws IOException
     */
    @PostMapping("/uploadImg")
    @ResponseBody
    @ApiOperation(value = "上传图片", httpMethod = "POST")
    public R uploadImgs(HttpServletRequest request) throws IOException {
        String s = new UploadImageUtil().uploadImage(request);
        return R.ok(s);
    }
}
